// 等待DOM加载完成
$(document).ready(function() {
    
    // 存储当前操作的申请ID
    let currentApplyId = null;
    // 存储选中的申请ID列表
    let selectedApplyIds = [];

    let currentPage = 1;
    let pageSize = 10;
    
    // 初始化表格数据
    initTableData();
    loadCertificationStats()
    /**
     * 加载认证统计数据
     */
    async function loadCertificationStats() {
        try {
            const response = await fetch('/system/GetCertificationStats', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (!response.ok) {
                throw new Error(`请求失败: ${response.statusText}`);
            }

            const result = await response.json();
            if (result.status === 0 && result.data) {
                const { 
                    pendingTotal, 
                    personalCert, 
                    enterpriseCert, 
                    mediaOrgCert, 
                    todayProcessed 
                } = result.data;

                // 更新数量显示
                $('#totalPending').text(pendingTotal.total || 0);
                $('#personalCount').text(personalCert.total || 0);
                $('#companyCount').text(enterpriseCert.total || 0);
                $('#orgCount').text(mediaOrgCert.total || 0);
                $('#todayProcessed').text(todayProcessed.total || 0);
                
                // 更新百分比指示器（关键修复：调整选择器匹配页面结构）
                updatePercentageIndicators({
                    pending: pendingTotal,
                    personal: personalCert,
                    company: enterpriseCert,
                    organization: mediaOrgCert,
                    todayProcessed: todayProcessed
                });
            }
        } catch (error) {
            console.error('加载统计数据失败:', error);
        }
    }

    /**
     * 更新百分比指示器
     * @param {Object} stats 统计数据对象
     */
    function updatePercentageIndicators(stats) {        
        // 待审核总数
        updateSingleIndicator('#totalPendingTrend', stats.pending);
        // 个人认证
        updateSingleIndicator('#personalCountTrend', stats.personal);
        // 企业认证
        updateSingleIndicator('#companyCountTrend', stats.company);
        // 媒体/机构
        updateSingleIndicator('#orgCountTrend', stats.organization);
        // 今日已处理
        updateSingleIndicator('#todayProcessedTrend', stats.todayProcessed);
    }

    /**
     * 更新单个指标的百分比显示
     * @param {string} selector 数值元素选择器
     * @param {Object} data 包含percent和trend的数据集
     */
    function updateSingleIndicator(selector, data) {
        // 获取百分比显示元素（紧跟在数值元素后面的兄弟元素）
        const indicatorEl = $(selector);
        if (indicatorEl.length === 0) return;

        const percent = data.percent || 0;
        const trend = data.trend; // 1: 上升, 0: 下降
        const arrowClass = trend === 1 ? 'fa-arrow-up text-danger' : 'fa-arrow-down text-success';
        console.log(data)
        // 更新百分比显示内容
        indicatorEl.html(`
            <span class="${trend === 1 ? 'text-danger' : 'text-success'} flex items-center">
                <i class="fa ${arrowClass} mr-1"></i> ${percent}%
            </span>
            <span class="text-neutral-400 ml-2">较昨日</span>
        `);
    }

    // 筛选按钮点击事件
    $('#filterBtn').click(function() {
        // 执行筛选逻辑
        filterCertifications();
    });

    // 分页按钮点击事件
    $(document).on('click', '.pagination-btn', function() {
        const page = parseInt($(this).data('page'));
        if (!isNaN(page) && page !== currentPage) {
            currentPage = page;
            initTableData()
        }
    });
    
    // 重置按钮点击事件
    $('#resetBtn').click(function() {
        // 重置筛选条件
        resetFilters();
    });
    
    // 全选复选框事件
    $('#selectAll').change(function() {
        const isChecked = $(this).is(':checked');
        $('.cert-item-checkbox').prop('checked', isChecked);
        
        // 更新选中的ID列表
        updateSelectedIds();
    });
    
    // 单选复选框事件委托
    $('#certificationTableBody').on('change', '.cert-item-checkbox', function() {
        // 检查是否所有单选框都被选中
        const allChecked = $('.cert-item-checkbox:checked').length === $('.cert-item-checkbox').length;
        $('#selectAll').prop('checked', allChecked);
        
        // 更新选中的ID列表
        updateSelectedIds();
    });
    
    // 批量认领按钮点击事件
    $('#batchClaimBtn').click(function() {
        if (selectedApplyIds.length === 0) return;
        
        // 显示认领模态框
        $('#claimModal').removeClass('hidden').addClass('flex');
    });
    
    // 批量通过按钮点击事件
    $('#batchApproveBtn').click(function() {
        if (selectedApplyIds.length === 0) return;
        
        // 显示审核模态框，默认选中通过
        $('#auditModalTitle').text('批量审核通过');
        $('#auditModalMessage').text(`您确定要批量通过选中的 ${selectedApplyIds.length} 项认证申请吗？`);
        $('input[name="auditResult"][value="2"]').prop('checked', true);
        $('#rejectReasonContainer').addClass('hidden');
        $('#auditModal').removeClass('hidden').addClass('flex');
    });
    
    // 批量拒绝按钮点击事件
    $('#batchRejectBtn').click(function() {
        if (selectedApplyIds.length === 0) return;
        
        // 显示审核模态框，选中拒绝
        $('#auditModalTitle').text('批量审核拒绝');
        $('#auditModalMessage').text(`您确定要批量拒绝选中的 ${selectedApplyIds.length} 项认证申请吗？`);
        $('input[name="auditResult"][value="3"]').prop('checked', true);
        $('#rejectReasonContainer').removeClass('hidden');
        $('#auditModal').removeClass('hidden').addClass('flex');
    });
    
    // 审核结果单选按钮事件
    $('input[name="auditResult"]').change(function() {
        const value = $(this).val();
        if (value === '3') {
            $('#rejectReasonContainer').removeClass('hidden');
        } else {
            $('#rejectReasonContainer').addClass('hidden');
        }
    });
    
    // 关闭详情模态框
    $('#closeDetailModal, #closeDetailBtn').click(function() {
        $('#detailModal').addClass('hidden').removeClass('flex');
    });
    
    // 取消审核按钮
    $('#cancelAuditBtn').click(function() {
        $('#auditModal').addClass('hidden').removeClass('flex');
    });
    
    // 确认审核按钮
    $('#confirmAuditBtn').click(function() {
        const auditResult = $('input[name="auditResult"]:checked').val();
        const rejectReason = auditResult === '3' ? $('#rejectReason').val() : '';
        const auditRemark = $('#auditRemark').val();
        
        // 执行审核操作
        performAudit(auditResult, rejectReason, auditRemark);
    });

    // 批量标记复查
    $('#batchReviewBtn').click(function() {
        if (selectedApplyIds.length === 0) {
            showToast('请选择要标记复查的申请', 'warning');
            return;
        };
        // 打开复查模态框
        $('#reviewModal').removeClass('hidden').addClass('flex');        
    })
    
    // 取消认领按钮
    $('#cancelClaimBtn').click(function() {
        $('#claimModal').addClass('hidden').removeClass('flex');
    });
    
    // 确认认领按钮
    $('#confirmClaimBtn').click(function() {
        // 执行认领操作
        performClaim();
    });
    
    // 处理审核按钮
    $('#handleDetailBtn').click(function() {
        $('#detailModal').addClass('hidden').removeClass('flex');
        $('#auditModalTitle').text('审核操作');
        $('#auditModalMessage').text(`请对申请ID: ${currentApplyId} 进行审核操作`);
        $('#auditModal').removeClass('hidden').addClass('flex');
        $('.cert-item-checkbox').each(function() {
            if($(this).data('id') == currentApplyId){
                $(this).prop('checked', true);
                console.log($(this).data('id'))
                updateSelectedIds();
                return true;
            }                
        });
    });

    $('#cancelReview').click(function() {
        $('#reviewModal').addClass('hidden').removeClass('flex');
    });

    $('#confirmReview').click(function() {
        batchOperate(selectedApplyIds, 'review', {
            reviewRemark: $('#reviewRemark').val(),
        }).then(() => {
                    // 刷新表格数据
                    initTableData();
                    // 清空选中项
                    selectedApplyIds = [];
                    $('#selectAll').prop('checked', false);
                    updateSelectedIds();
                    // 显示成功提示
                    showToast('标记复查成功', 'success');
                    // 隐藏模态框
                    $('#reviewModal').addClass('hidden').removeClass('flex');
                }).catch(error => {
                    showToast(error.message || '标记复查失败', 'error');
                });
    });

    /**
     * 渲染分页控件
     * @param {number} total - 总记录数
     * @param {number} currentPage - 当前页码
     * @param {number} pageSize - 每页条数
     */
    function renderPagination(total, currentPage, pageSize) {
        const totalPages = Math.ceil(total / pageSize);
        const paginationContainer = $('#certificationPagination'); // 分页容器
        
        // 清空现有分页
        paginationContainer.empty();
        
        // 上一页按钮
        const prevDisabled = currentPage === 1 ? 'disabled' : '';
        paginationContainer.append(`
            <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                    data-page="${currentPage - 1}" ${prevDisabled}>
                <i class="fa fa-angle-left"></i>
            </button>
        `);
        
        // 页码按钮（最多显示5个页码）
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        
        // 调整显示范围
        if (endPage - startPage < 4 && totalPages > 5) {
            startPage = Math.max(1, endPage - 4);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const isActive = i === currentPage ? 'border-primary bg-primary text-white' : 'border-neutral-200 text-neutral-700 hover:border-primary hover:text-primary';
            paginationContainer.append(`
                <button class="w-8 h-8 flex items-center justify-center rounded ${isActive} pagination-btn" data-page="${i}">
                    ${i}
                </button>
            `);
        }
        
        // 下一页按钮
        const nextDisabled = currentPage === totalPages ? 'disabled' : '';
        paginationContainer.append(`
            <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                    data-page="${currentPage + 1}" ${nextDisabled}>
                <i class="fa fa-angle-right"></i>
            </button>
        `);
        
        // 更新分页信息
        const start = total > 0 ? (currentPage - 1) * pageSize + 1 : 0;
        const end = Math.min(currentPage * pageSize, total);
        $('.pagenation').text(`显示 ${start} 至 ${end} 条，共 ${total} 条`);
    }
    /**
     * 获取筛选参数
     */
    /**
     * 获取筛选参数
     */
    function getFilterParams() {
        return {
            page:currentPage,
            pageSize,
            claimStatus: $('#claimStatusFilter').val(),
            auditStatus: $('#auditStatusFilter').val(),
            certType: $('#certTypeFilter').val(),
            keyword: $('#keywordSearch').val().trim(),
            startDate: $('#startDate').val(),
            endDate: $('#endDate').val()
        };
    }

    /**
     * 获取举报列表
     * @param {*} params 
     * @returns 
     * */
    async function fetchCollectionList(params) {
        try {
            // 构建查询字符串
            const queryParams = new URLSearchParams();
            Object.entries(params).forEach(([key, value]) => {
                if (value !== undefined && value !== null && value !== '') {
                    queryParams.append(key, value);
                }
            });

            // 发起请求
            const response = await fetch(`/system/GetCertApplyList?${queryParams.toString()}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    // 根据实际需求添加认证信息
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
            if (response.status/1 != 200) {
                throw new Error(`请求失败: ${response.statusText}`);
            }

            const data = await response.json();
            return data;
        } catch (error) {
            showToast(error.message || '获取媒体内容列表失败');
        }
    }

    /**
     * 批量操作API调用
     */
    async function batchOperate(ids, action, extraParams = {}) {
        try {
            let url = '';
            let requestData = { ids: ids, ...extraParams };

            switch(action) {
                case 'approve':
                    url = '/system/BatchAuditPassCert';
                    break;
                case 'reject':
                    url = '/system/BatchAuditRejectCert';
                    const rejectReason = $('#rejectReason').val().trim();
                    if (!rejectReason) {
                        throw new Error('请输入拒绝原因');
                    }
                    requestData.rejectReason = rejectReason;
                    break;
                case 'claim':
                    url = '/system/BatchClaimCert';
                    break;
                case 'review':
                    url = '/system/BatchReviewCert';
                    break;
                case 'audit':
                    url = '/system/AuditCert';
                    break;
                default:
                    throw new Error('不支持的操作类型');
            }

            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify(requestData)
            });

            const result = await response.json();
            
            if (!response.ok || result.status / 1 !== 0) {
                throw new Error(result.msg || `操作失败: ${response.statusText}`);
            }
            
            return result;
        } catch (error) {
            throw error;
        }
    }
    
    // 初始化表格数据
    function initTableData() {
        
        // 显示加载中状态
        $('#certificationTableBody').html('<tr><td colspan="9" class="text-center py-4">加载中...</td></tr>');
        
        // 获取筛选参数
        const params = getFilterParams();
        
        // 调用后端接口获取数据
        fetchCollectionList(params)
            .then(result => {
                renderTable(result.data.list);
                renderPagination(result.data.total, currentPage, pageSize);
            })
            .catch(error => {
                // console.error('加载数据失败:', error);
                $('#certificationTableBody').html('<tr><td colspan="8" class="text-center py-4 text-danger">加载数据失败，请重试</td></tr>');
            });
    }
    
    // 渲染表格
    function renderTable(data) {
        const tableBody = $('#certificationTableBody');
        tableBody.empty();
        const certTypeMap = {
            '1': '个人认证',
            '2': '企业认证',
            '3': '媒体认证',
            '4': '党政机关认证',
            '5': '其他组织认证'
        };
        data.forEach(item => {
            // 审核状态样式
            let statusClass = '';
            switch(item.audit_status) {
                case 1: statusClass = 'bg-pending/10 text-pending'; break;
                case 2: statusClass = 'bg-success/10 text-success'; break;
                case 3: statusClass = 'bg-danger/10 text-danger'; break;
                case 4: statusClass = 'bg-neutral-100 text-neutral-500'; break;
            }

            let statusStyle = '';
            switch(item.audit_status) {
                case '1':
                    statusStyle = '<span class="px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-600">待审核</span>';
                    break;
                case '2':
                    statusStyle = '<span class="px-2 py-1 text-xs rounded-full bg-green-100 text-green-600">通过</span>';
                    break;
                case '3':
                    statusStyle = '<span class="px-2 py-1 text-xs rounded-full bg-red-100 text-red-600">拒绝</span>';
                    break;
                case '4':
                    statusStyle = '<span class="px-2 py-1 text-xs rounded-full bg-orange-100 text-orange-600">再次审核</span>';
                    break;
                default:
                    statusStyle = `<span class="px-2 py-1 text-xs rounded-full bg-neutral-100 text-neutral-500">${auditStatus}</span>`;
            }
            
            // 认领状态
            const claimStatus = item.claimed_status/1 === 2 ? 
                `<span class="text-xs px-2 py-0.5 rounded-full bg-primary/10 text-primary">已认领 by ${item.claimed_by_name}</span>` : 
                `<span class="text-xs px-2 py-0.5 rounded-full bg-neutral-100 text-neutral-500">未认领</span>`;
            
            // 操作按钮
            let actionButtons = '';
            let actionButtons1 = '';
            if(item.claimed_status/1 == 1){
                // 已认领
                actionButtons1 = `
                    <button class="text-secondary hover:text-secondary/80 mr-3 claim-btn" data-id="${item.apply_id}">认领</button>
                `;
            }
            
            if (item.audit_status/1 === 1) {
                // 待审核状态
                actionButtons = `
                    <button class="text-primary hover:text-primary/80 mr-3 view-detail" data-id="${item.apply_id}" title="查看详情">
                        <i class="fa fa-eye"></i>
                    </button>
                    
                    <button class="text-success hover:text-success/80 approve-btn" data-id="${item.apply_id}" title="通过">
                        <i class="fa fa-check"></i>
                    </button>

                    <button class="text-danger hover:text-danger/80 reject-btn" data-id="${item.apply_id}" title="拒绝">
                        <i class="fa fa-times"></i>
                    </button>
                `;
            } else if(item.audit_status/1 == 2){
                // 审核通过
                actionButtons = `
                    <button class="text-primary hover:text-primary/80 mr-3 view-detail" data-id="${item.apply_id}" title="查看详情">
                        <i class="fa fa-eye"></i>
                    </button>
                    <button class="text-secondary hover:text-secondary/80 mr-3 review-btn" data-id="${item.apply_id}" title="标记为复查">
                        <i class="fa fa-repeat"></i>
                    </button>
                `;
            } else if(item.audit_status/1 == 3){
                // 审核拒绝
                actionButtons = `
                    <button class="text-primary hover:text-primary/80 mr-3 view-detail" data-id="${item.apply_id}" title="查看详情">
                        <i class="fa fa-eye"></i>
                    </button>
                `;
            } else if(item.audit_status/1 == 4){
                // 再次审核
                actionButtons = `
                    <button class="text-primary hover:text-primary/80 mr-3 view-detail" data-id="${item.apply_id}" title="查看详情">
                        <i class="fa fa-eye"></i>
                    </button>
                    <button class="text-success hover:text-success/80 approve-btn" data-id="${item.apply_id}" title="通过">
                        <i class="fa fa-check"></i>
                    </button>
                    
                    <button class="text-danger hover:text-danger/80 reject-btn" data-id="${item.apply_id}" title="拒绝">
                        <i class="fa fa-times"></i>
                    </button>
                `;
            } else {
                actionButtons = `
                    <button class="text-primary hover:text-primary/80 mr-3 view-detail" data-id="${item.apply_id}" title="查看详情">
                        <i class="fa fa-eye"></i>
                    </button>
                `;
            }

            const cert_type_text = certTypeMap[item.cert_type] || '未知状态';
            
            const row = `
                <tr>
                    <td class="px-5 py-4 whitespace-nowrap">
                        <input type="checkbox" class="cert-item-checkbox rounded border-neutral-300 text-primary focus:ring-primary" data-id="${item.apply_id}">
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap text-sm">${item.apply_id}</td>
                    <td class="px-5 py-4 whitespace-nowrap text-sm">${cert_type_text}</td>
                    <td class="px-5 py-4 whitespace-nowrap text-sm">${item.realname}</td>
                    <td class="px-5 py-4 whitespace-nowrap text-sm text-neutral-500">${item.apply_time}</td>
                    <td class="px-5 py-4 whitespace-nowrap">${claimStatus}</td>
                    <td class="px-5 py-4 whitespace-nowrap">
                        <span class="text-xs px-2 py-0.5 rounded-full ${statusClass}">${statusStyle}</span>
                    </td>
                    <td class="px-5 py-4 whitespace-nowrap text-sm">${item.chk_num}</td>
                    <td class="px-5 py-4 whitespace-nowrap text-sm">
                        ${actionButtons}${actionButtons1}
                    </td>
                </tr>
            `;
            
            tableBody.append(row);
        });
        
        // 绑定查看详情事件
        $('.view-detail').click(function() {
            const applyId = $(this).data('id');
            viewDetail(applyId);
        });
        
        // 绑定认领事件
        $('.claim-btn').click(function() {
            batchOperate([$(this).data('id')], 'claim', {}).then(() => {
                // 刷新表格数据
                initTableData();
                // 清空选中项
                selectedApplyIds = [];
                $('#selectAll').prop('checked', false);
                updateSelectedIds();
            });
        });
        
        // 绑定通过事件
        $('.approve-btn').click(function() {
            currentApplyId = $(this).data('id');
            $('#auditModalTitle').text('审核通过');
            $('#auditModalMessage').text(`您确定要通过申请ID: ${currentApplyId} 的认证申请吗？`);
            $('input[name="auditResult"][value="2"]').prop('checked', true);
            $('#rejectReasonContainer').addClass('hidden');
            $('#auditModal').removeClass('hidden').addClass('flex');
            $('.cert-item-checkbox').each(function() {
                if($(this).data('id') == currentApplyId){
                    $(this).prop('checked', true);
                    console.log($(this).data('id'))
                    updateSelectedIds();
                    return true;
                }                
            });
        });

        // 标记未复查
        $('.review-btn').click(function() {
            currentApplyId = $(this).data('id');
            
            // 打开复查模态框
            $('#reviewModal').removeClass('hidden').addClass('flex');  

            $('.cert-item-checkbox').each(function() {
                if($(this).data('id') == currentApplyId){
                    $(this).prop('checked', true);
                    console.log($(this).data('id'))
                    updateSelectedIds();
                    return true;
                }                
            });

        })
        
        // 绑定拒绝事件
        $('.reject-btn').click(function() {
            currentApplyId = $(this).data('id');
            $('#auditModalTitle').text('审核拒绝');
            $('#auditModalMessage').text(`您确定要拒绝申请ID: ${currentApplyId} 的认证申请吗？`);
            $('input[name="auditResult"][value="3"]').prop('checked', true);
            $('#rejectReasonContainer').removeClass('hidden');
            $('#auditModal').removeClass('hidden').addClass('flex');
            $('.cert-item-checkbox').each(function() {
                if($(this).data('id') == currentApplyId){
                    $(this).prop('checked', true);
                    updateSelectedIds();
                    return true;
                }                
            });
        });
    }
    
    // 更新选中的ID列表
    function updateSelectedIds() {
        selectedApplyIds = [];
        $('.cert-item-checkbox:checked').each(function() {
            selectedApplyIds.push($(this).data('id'));
        });
        
        // 更新选中数量显示
        $('#selectedCount').text(`已选择 ${selectedApplyIds.length} 项`);
        
        // 启用/禁用批量操作按钮
        const hasSelected = selectedApplyIds.length > 0;
        $('#batchClaimBtn').prop('disabled', !hasSelected);
        $('#batchApproveBtn').prop('disabled', !hasSelected);
        $('#batchRejectBtn').prop('disabled', !hasSelected);
    }
    /**
     * 获取规则通用方法
     * @returns {Promise}
     */
    async function getApplyId(id) {
        try {
            let url = '';

            url = '/system/GetCertDetail?applyId='+id;

            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            const result = await response.json();
            
            if (!response.ok || result.status/1 !== 0) {
                throw new Error(result.msg || `操作失败: ${response.statusText}`);
            }
            
            return result.data;
        } catch (error) {
            throw error; // 抛出错误给调用方处理
        }
    }
    // 查看详情
function viewDetail(applyId) {
    currentApplyId = applyId;
    $('#detailTitle').text(`认证申请详情 (${applyId})`);
    
    // 显示加载状态
    $('#detailContent').html(`
        <div class="flex justify-center items-center py-10">
            <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary"></div>
            <span class="ml-2 text-neutral-600">加载中...</span>
        </div>
    `);
    $('#detailModal').removeClass('hidden').addClass('flex');

    // 从接口获取认证申请详情
    getApplyId(applyId).then(data => {
        // 定义数据映射关系
        const certTypeMap = {
            '1': '个人认证',
            '2': '企业认证',
            '3': '媒体认证',
            '4': '党政机关认证',
            '5': '其他组织认证'
        };
        
        const auditStatusMap = {
            '1': { text: '待审核', class: 'text-blue-600' },
            '2': { text: '审核通过', class: 'text-green-600' },
            '3': { text: '审核拒绝', class: 'text-red-600' },
            '4': { text: '已撤回', class: 'text-neutral-500' }
        };
        
        const identityMap = {
            '1': '法定代表人',
            '2': '代理人'
        };

        // 处理证件号码脱敏
        const maskIdNumber = (id) => {
            if (!id) return '-';
            return id.substr(0, 6) + '************' + id.substr(-4);
        };

        // 处理手机号脱敏
        const maskPhone = (phone) => {
            if (!phone) return '-';
            return phone.substr(0, 3) + '****' + phone.substr(-4);
        };

        // 生成基本信息HTML
        let basicInfoHtml = `
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                <div>
                    <p class="text-neutral-500">申请ID</p>
                    <p class="font-medium">${data.apply_id || '-'}</p>
                </div>
                <div>
                    <p class="text-neutral-500">认证类型</p>
                    <p class="font-medium">${certTypeMap[data.cert_type] || '-'}</p>
                </div>
                <div>
                    <p class="text-neutral-500">申请人姓名</p>
                    <p class="font-medium">${data.realname || '-'}</p>
                </div>
                <div>
                    <p class="text-neutral-500">证件号码</p>
                    <p class="font-medium">${maskIdNumber(data.id_number)}</p>
                </div>
                <div>
                    <p class="text-neutral-500">联系电话</p>
                    <p class="font-medium">${maskPhone(data.contact_phone)}</p>
                </div>
                <div>
                    <p class="text-neutral-500">联系邮箱</p>
                    <p class="font-medium">${data.contact_email || '-'}</p>
                </div>
                <div>
                    <p class="text-neutral-500">申请时间</p>
                    <p class="font-medium">${data.apply_time || '-'}</p>
                </div>
                <div>
                    <p class="text-neutral-500">当前状态</p>
                    <p class="font-medium ${auditStatusMap[data.audit_status]?.class || ''}">
                        ${auditStatusMap[data.audit_status]?.text || '-'}
                    </p>
                </div>
        `;

        // 企业/组织额外信息
        if ([2, 3, 4, 5].includes(Number(data.cert_type))) {
            basicInfoHtml += `
                <div>
                    <p class="text-neutral-500">单位名称</p>
                    <p class="font-medium">${data.company_name || '-'}</p>
                </div>
                <div>
                    <p class="text-neutral-500">统一社会信用代码</p>
                    <p class="font-medium">${data.company_number || '-'}</p>
                </div>
                <div>
                    <p class="text-neutral-500">单位地址</p>
                    <p class="font-medium">${data.company_address || '-'}</p>
                </div>
                <div>
                    <p class="text-neutral-500">单位官网</p>
                    <p class="font-medium">${data.company_url ? `<a href="${data.company_url}" target="_blank" class="text-primary hover:underline">${data.company_url}</a>` : '-'}</p>
                </div>
                <div>
                    <p class="text-neutral-500">法定代表人</p>
                    <p class="font-medium">${data.legal_rep_name || '-'}</p>
                </div>
                <div>
                    <p class="text-neutral-500">填写人身份</p>
                    <p class="font-medium">${identityMap[data.writer_identity] || '-'}</p>
                </div>
            `;
        }

        basicInfoHtml += `</div>`;

        // 生成证件材料HTML
        let materialsHtml = `<div class="grid grid-cols-1 md:grid-cols-3 gap-4">`;
        
        // 身份证材料（所有类型都可能有）
        if (data.id_photo_front) {
            materialsHtml += `
                <div>
                    <p class="text-neutral-500 text-sm mb-1">身份证正面</p>
                    <div class="border border-neutral-200 rounded-lg overflow-hidden cursor-pointer preview-img" data-img="${data.id_photo_front}">
                        <img src="${data.id_photo_front}" alt="身份证正面" class="w-full h-48 object-cover">
                    </div>
                </div>
            `;
        }
        
        if (data.id_photo_back) {
            materialsHtml += `
                <div>
                    <p class="text-neutral-500 text-sm mb-1">身份证反面</p>
                    <div class="border border-neutral-200 rounded-lg overflow-hidden cursor-pointer preview-img" data-img="${data.id_photo_back}">
                        <img src="${data.id_photo_back}" alt="身份证反面" class="w-full h-48 object-cover">
                    </div>
                </div>
            `;
        }
        
        if (data.id_photo_hold) {
            materialsHtml += `
                <div>
                    <p class="text-neutral-500 text-sm mb-1">手持身份证</p>
                    <div class="border border-neutral-200 rounded-lg overflow-hidden cursor-pointer preview-img" data-img="${data.id_photo_hold}">
                        <img src="${data.id_photo_hold}" alt="手持身份证" class="w-full h-48 object-cover">
                    </div>
                </div>
            `;
        }
        
        // 企业/组织证件
        if (data.company_certificate) {
            materialsHtml += `
                <div>
                    <p class="text-neutral-500 text-sm mb-1">单位证件</p>
                    <div class="border border-neutral-200 rounded-lg overflow-hidden cursor-pointer preview-img" data-img="${data.company_certificate}">
                        <img src="${data.company_certificate}" alt="单位证件" class="w-full h-48 object-cover">
                    </div>
                </div>
            `;
        }
        
        // 法定代表人证件
        if (data.legal_rep_id_photo_front) {
            materialsHtml += `
                <div>
                    <p class="text-neutral-500 text-sm mb-1">法定代表人身份证正面</p>
                    <div class="border border-neutral-200 rounded-lg overflow-hidden cursor-pointer preview-img" data-img="${data.legal_rep_id_photo_front}">
                        <img src="${data.legal_rep_id_photo_front}" alt="法定代表人身份证正面" class="w-full h-48 object-cover">
                    </div>
                </div>
            `;
        }
        
        if (data.legal_rep_id_photo_back) {
            materialsHtml += `
                <div>
                    <p class="text-neutral-500 text-sm mb-1">法定代表人身份证反面</p>
                    <div class="border border-neutral-200 rounded-lg overflow-hidden cursor-pointer preview-img" data-img="${data.legal_rep_id_photo_back}">
                        <img src="${data.legal_rep_id_photo_back}" alt="法定代表人身份证反面" class="w-full h-48 object-cover">
                    </div>
                </div>
            `;
        }
        
        // 代理人授权书
        if (data.agent_authorization) {
            materialsHtml += `
                <div>
                    <p class="text-neutral-500 text-sm mb-1">代理人授权书</p>
                    <div class="border border-neutral-200 rounded-lg overflow-hidden cursor-pointer preview-img" data-img="${data.agent_authorization}">
                        <img src="${data.agent_authorization}" alt="代理人授权书" class="w-full h-48 object-cover">
                    </div>
                </div>
            `;
        }
        
        if (materialsHtml === `<div class="grid grid-cols-1 md:grid-cols-3 gap-4">`) {
            materialsHtml += `<p class="col-span-full text-center py-4 text-neutral-500">暂无证件材料</p>`;
        }
        materialsHtml += `</div>`;

        // 生成审核记录HTML
        let auditRecordsHtml = `<div class="space-y-3 text-sm">`;
        
        // 提交申请记录
        auditRecordsHtml += `
            <div class="p-3 bg-neutral-50 rounded-lg">
                <div class="flex justify-between">
                    <p class="font-medium">提交申请</p>
                    <p class="text-neutral-500">${data.apply_time || '-'}</p>
                </div>
                <p class="text-neutral-500 mt-1">用户提交了${certTypeMap[data.cert_type]}申请</p>
            </div>
        `;
        
        // 认领记录
        if (data.claimed_time && data.claimed_by) {
            auditRecordsHtml += `
                <div class="p-3 bg-neutral-50 rounded-lg">
                    <div class="flex justify-between">
                        <p class="font-medium">已认领</p>
                        <p class="text-neutral-500">${data.claimed_time}</p>
                    </div>
                    <p class="text-neutral-500 mt-1">审核员ID: ${data.claimed_by} 认领了该申请</p>
                </div>
            `;
        }
        
        // 审核记录
        if (data.checked_time && data.checked_by) {
            const statusText = auditStatusMap[data.audit_status]?.text || '已审核';
            let reasonHtml = '';
            if (data.audit_status === '3' && data.fail_reason) {
                reasonHtml = `<p class="text-neutral-500 mt-1">拒绝原因: ${data.fail_reason}</p>`;
            }
            
            auditRecordsHtml += `
                <div class="p-3 bg-neutral-50 rounded-lg">
                    <div class="flex justify-between">
                        <p class="font-medium ${auditStatusMap[data.audit_status]?.class || ''}">${statusText}</p>
                        <p class="text-neutral-500">${data.checked_time}</p>
                    </div>
                    <p class="text-neutral-500 mt-1">审核员ID: ${data.checked_by}</p>
                    ${reasonHtml}
                </div>
            `;
        }
        
        auditRecordsHtml += `</div>`;

        // 组合完整HTML
        const detailHtml = `
            <div class="space-y-6">
                <div class="border border-neutral-200 rounded-lg p-4">
                    <h4 class="font-medium mb-3 flex items-center">
                        <i class="fa fa-info-circle text-primary mr-2"></i>基本信息
                    </h4>
                    ${basicInfoHtml}
                </div>
                
                <div class="border border-neutral-200 rounded-lg p-4">
                    <h4 class="font-medium mb-3 flex items-center">
                        <i class="fa fa-id-card text-primary mr-2"></i>证件材料
                    </h4>
                    ${materialsHtml}
                </div>
                
                <div class="border border-neutral-200 rounded-lg p-4">
                    <h4 class="font-medium mb-3 flex items-center">
                        <i class="fa fa-history text-primary mr-2"></i>审核记录
                    </h4>
                    ${auditRecordsHtml}
                </div>
            </div>
        `;
        
        $('#detailContent').html(detailHtml);
        
        // 绑定图片预览事件
        $('.preview-img').click(function() {
            const imgSrc = $(this).data('img');
            showImagePreview(imgSrc);
        });

    }).catch(error => {
        console.error('获取认证申请详情失败:', error);
        $('#detailContent').html(`
            <div class="py-10 text-center">
                <i class="fa fa-exclamation-circle text-danger text-xl mb-2"></i>
                <p class="text-neutral-600">获取详情失败，请重试</p>
                <button onclick="viewDetail('${applyId}')" class="mt-3 px-4 py-1 bg-primary text-white rounded hover:bg-primary/90">
                    重新加载
                </button>
            </div>
        `);
    });
}

    
    // 显示图片预览
    function showImagePreview(src) {
        // 创建图片预览弹窗
        const previewHtml = `
            <div class="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4" id="imagePreviewModal">
                <button class="absolute top-4 right-4 text-white text-2xl" id="closeImagePreview">
                    <i class="fa fa-times"></i>
                </button>
                <img src="${src}" alt="预览图片" class="max-w-full max-h-[90vh] object-contain">
            </div>
        `;
        
        $('body').append(previewHtml);
        
        // 绑定关闭事件
        $('#closeImagePreview').click(function() {
            $('#imagePreviewModal').remove();
        });
        
        // 点击背景关闭
        $('#imagePreviewModal').click(function(e) {
            if (e.target === this) {
                $('#imagePreviewModal').remove();
            }
        });
    }
    
    // 执行筛选
    function filterCertifications() {
        const certType = $('#certTypeFilter').val();
        const auditStatus = $('#auditStatusFilter').val();
        const sortType = $('#sortFilter').val();
        const keyword = $('#keywordSearch').val();
        const name = $('#nameSearch').val();
        const startDate = $('#startDate').val();
        const endDate = $('#endDate').val();
        const auditor = $('#auditorSearch').val();
        
        // 这里可以根据筛选条件向后端请求数据
        // 为了演示，我们重新加载模拟数据
        initTableData();
        
        // 显示筛选提示
        showToast('筛选条件已应用', 'success');
    }
    
    // 重置筛选条件
    function resetFilters() {
        $('#certTypeFilter').val(0);
        $('#auditStatusFilter').val(0);
        $('#sortFilter').val(0);
        $('#keywordSearch').val('');
        $('#nameSearch').val('');
        $('#startDate').val('');
        $('#endDate').val('');
        $('#auditorSearch').val('');
        
        // 重新加载数据
        initTableData();
    }
    
    // 执行认领操作
    function performClaim() {
        // 关闭模态框
        $('#claimModal').addClass('hidden').removeClass('flex');

        batchOperate(selectedApplyIds, 'claim', {}).then(() => {
            // 刷新表格数据
            initTableData();
            // 清空选中项
            selectedApplyIds = [];
            $('#selectAll').prop('checked', false);
            updateSelectedIds();
            // 显示成功提示
            showToast('认领成功', 'success');
        }).catch(error => {
            showToast(error.message || '认领失败', 'error');
        });
    }
    
    // 执行审核操作
    function performAudit(auditResult, rejectReason, auditRemark) {
        // 关闭模态框
        $('#auditModal').addClass('hidden').removeClass('flex');
        
        switch(auditResult) {
            case '2':
                rejectReason = '';
                auditRemark = '';
                batchOperate(selectedApplyIds, 'approve', {
                    auditResult: auditResult,
                    rejectReason: rejectReason,
                    auditRemark: auditRemark
                }).then(() => {
                    // 刷新表格数据
                    initTableData();
                    // 清空选中项
                    selectedApplyIds = [];
                    $('#selectAll').prop('checked', false);
                    updateSelectedIds();
                    // 显示成功提示
                    showToast('审核操作成功', 'success');
                }).catch(error => {
                    showToast(error.message || '审核操作失败', 'error');
                });
                break;
            case '3':
                rejectReason = rejectReason || '';
                auditRemark = '';
                batchOperate(selectedApplyIds, 'reject', {
                    auditResult: auditResult,
                    rejectReason: rejectReason,
                    auditRemark: auditRemark
                }).then(() => {
                    // 刷新表格数据
                    initTableData();
                    // 清空选中项
                    selectedApplyIds = [];
                    $('#selectAll').prop('checked', false);
                    updateSelectedIds();
                    // 显示成功提示
                    showToast('审核操作成功', 'success');
                }).catch(error => {
                    showToast(error.message || '审核操作失败', 'error');
                });
                break;
                
        }
    }
    
    // Toast提示函数（复用layout.html中的实现）
    function showToast(message, type = 'info', duration = 3000) {
        // 移除已存在的toast
        $('.toast').remove();
        
        // 获取对应类型的图标
        function getToastIcon(type) {
            switch(type) {
                case 'success': return 'fa-check-circle';
                case 'error': return 'fa-times-circle';
                case 'warning': return 'fa-exclamation-triangle';
                case 'info': return 'fa-info-circle';
                default: return 'fa-info-circle';
            }
        }
        
        // 创建toast元素
        const toast = $(`
            <div class="toast toast-top-center toast-hidden toast-${type}">
                <i class="fa toast-icon ${getToastIcon(type)}"></i>
                <span>${message}</span>
            </div>
        `);
        
        // 添加到页面
        $('body').append(toast);
        
        // 显示toast
        setTimeout(() => {
            toast.removeClass('toast-hidden');
        }, 10);
        
        // 自动隐藏
        setTimeout(() => {
            toast.addClass('toast-hidden');
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, duration);
    }
});